package com.zijidelu.luframework.api.controller;

import com.zijidelu.luframework.application.service.AppService;
import com.zijidelu.luframework.base.model.DataModel;
import com.zijidelu.luframework.api.model.ApiRequest;
import com.zijidelu.luframework.api.model.ApiResult;
import com.zijidelu.luframework.api.model.Request;
import com.zijidelu.luframework.api.model.Response;
import com.zijidelu.luframework.base.message.impl.GenericMessage;
import com.zijidelu.luframework.base.valid.BaseValid;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.List;

/**
 * @author ZIJIDELU
 * @datetime 2025/11/8 17:36
 */
public interface WriterController<D extends DataModel, R extends Response, Q extends Request> extends DataConversionSupport<D, R, Q> {
    AppService<D> getAppService();

    /**
     * 保存数据列表。
     *
     * @param request 数据请求列表
     * @return 操作结果
     */
    default ApiResult<String> save(@Validated({BaseValid.class}) ApiRequest<List<Q>> request) {
        if (request == null || request.getPayload() == null || request.getPayload().isEmpty()) {
            return ApiResult.failOf("request 为必填项");
        }

        final List<D> dtoList = getDataRequestConverter().requestToDtoList(request.getPayload());
        final boolean saved = getAppService().save(dtoList);
        return ApiResult.toResult(GenericMessage.of(saved));
    }

    /**
     * 更新数据列表。
     *
     * @param request 数据请求列表
     * @return 操作结果
     */
    default ApiResult<String> update(@Validated({BaseValid.class}) ApiRequest<List<Q>> request) {
        if (request == null || request.getPayload() == null || request.getPayload().isEmpty()) {
            return ApiResult.failOf("request 为必填项");
        }

        final List<D> dtoList = getDataRequestConverter().requestToDtoList(request.getPayload());
        final boolean updated = getAppService().update(dtoList);
        return ApiResult.toResult(GenericMessage.of(updated));
    }

    /**
     * 根据ID列表批量删除数据。
     *
     * @param ids 数据ID列表
     * @return 操作结果
     */
    default ApiResult<String> deleteByIds(@Validated({BaseValid.class}) ApiRequest<Collection<Long>> ids) {
        if (ids == null || ids.getPayload() == null || ids.getPayload().isEmpty()) {
            return ApiResult.failOf("id列表 为必填项");
        }

        final boolean deleted = getAppService().deleteById(ids.getPayload());
        return ApiResult.toResult(GenericMessage.of(deleted));
    }
}
